# frozen_string_literal: true

class CouponController < ApplicationController
  wechat_api
  def receive
    @current_user = User.find(session['user_id'])
    city = @current_user.address.city if @current_user.address
    @coupon_list = []
    _item_name = @current_user.coupons.pluck(:name).uniq
    name_list = Coupon.pluck(:name).uniq
    name_list.each do |_item|
      next if _item_name.include?(_item)
      @coupon = Coupon.where(name: _item, receive: false, state: true).first
      if @coupon.nil? || @coupon.limit_state
        @coupons = Coupon.where(name: _item, receive: false, region: city.to_s, state: true)
        @coupon_list << @coupons.sample if @coupons.any?
      else
        @coupons = Coupon.where(name: _item, receive: false, state: true)
        @coupon_list << @coupons.sample if @coupons.any?
      end
    end
  end

  def my_coupons
    @current_user = User.find(session['user_id'])
    @coupons = @current_user.coupons
 end

  def add
    @current_user = User.find(session['user_id'])
    @coupon = Coupon.find(params[:id])
    @coupon.user_id = @current_user.id
    @coupon.receive = true
    @coupon.save
  end

  def show
    @coupon = Coupon.find_by_code(params[:code])
  end
end
